package com.ztom.top100;

import java.util.List;

/**
 * 单词拆分
 * <p>
 * https://leetcode-cn.com/problems/word-break/
 *
 * @author ZhangTao
 */
public class Code49WordBreak {

    public boolean wordBreak1(String s, List<String> wordDict) {
        if (s == null || s.length() == 0
                || wordDict == null || wordDict.size() == 0) {
            return false;
        }

        return process(s, wordDict, 0);
    }

    /**
     * 已匹配的前缀切掉, 剩下部分继续匹配
     *
     * @param s
     * @param wordDict
     * @param i
     * @return
     */
    private boolean process(String s, List<String> wordDict, int i) {
        if (i == s.length()) {
            // 全部切割完
            return true;
        }

        for (int j = i + 1; j <= s.length(); j++) {
            if (wordDict.contains(s.substring(i, j))
                    // 左部分已匹配, 继续去右部分匹配
                    && process(s, wordDict, j)) {

                // [i, j) 和 [j, len) 都匹配
                return true;
            }
        }

        return false;
    }

    public boolean wordBreak(String s, List<String> wordDict) {
        if (s == null || s.length() == 0
                || wordDict == null || wordDict.size() == 0) {
            return false;
        }

        int n = s.length();
        boolean[] dp = new boolean[n + 1];
        dp[n] = true;

        for (int i = n - 1; i >= 0; i--) {
            for (int j = i + 1; j <= n; j++) {
                if (wordDict.contains(s.substring(i, j)) && dp[j]) {
                    dp[i] = true;
                    break;
                }
            }
        }

        return dp[0];
    }
}
